﻿Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.DirectoryServices
Imports System.Text

Namespace System.Workflow.Activities
    <Serializable> _
    Friend NotInheritable Class DirectoryGroupQuery
        Implements IDirectoryOperation
        ' Methods
        Private Shared Function BuildUri(ByVal propValue As String) As String
            Dim builder As New StringBuilder
            builder.Append("LDAP://")
            Dim i As Integer
            For i = 0 To propValue.Length - 1
                If (propValue.Chars(i) = "/"c) Then
                    builder.Append("\/")
                Else
                    builder.Append(propValue.Chars(i))
                End If
            Next i
            Return builder.ToString
        End Function

        Private Shared Function Contains(ByVal propertyNames As ICollection, ByVal testPropertyName As String) As Boolean
            Dim str As String
            For Each str In propertyNames
                If (String.Compare(str, testPropertyName, StringComparison.Ordinal) = 0) Then
                    Return True
                End If
            Next
            Return False
        End Function

        Public Sub GetResult(ByVal rootEntry As DirectoryEntry, ByVal currentEntry As DirectoryEntry, ByVal response As List([Of] DirectoryEntry))
            If (response Is Nothing) Then
                Throw New ArgumentNullException("response")
            End If
            Dim stack As New Stack([Of] DirectoryEntry)
            stack.Push(currentEntry)
            Do While (stack.Count <> 0)
                Dim item As DirectoryEntry = stack.Pop
                Dim flag As Boolean = False
                If DirectoryGroupQuery.Contains(item.Properties.PropertyNames, "objectClass") Then
                    Dim str As String
                    For Each str In item.Properties.Item("objectClass")
                        If (String.Compare(str, ActiveDirectoryRoleFactory.Configuration.Group, StringComparison.Ordinal) = 0) Then
                            flag = True
                            Exit For
                        End If
                    Next
                    If flag Then
                        If DirectoryGroupQuery.Contains(item.Properties.PropertyNames, ActiveDirectoryRoleFactory.Configuration.Member) Then
                            Dim str2 As String
                            For Each str2 In item.Properties.Item(ActiveDirectoryRoleFactory.Configuration.Member)
                                stack.Push(New DirectoryEntry(DirectoryGroupQuery.BuildUri(str2)))
                            Next
                        End If
                    Else
                        response.Add(item)
                    End If
                End If
            Loop
        End Sub

    End Class
End Namespace

